<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

// 为方便系统核心升级，二次开发中需要用到的公共函数请写在这个文件，不要去修改common.php文件
use think\Db;
use think\Container;
use think\facade\Env;
use app\user\model\User;

//生成用户Id
function create_userId()
{
        $username = rand(1000000,9999999);
        $has = Db::name('user')->where('username',$username)->find();
        if (empty($has)) {
            return $username;
        }
       return create_userId();
}
function rongcloud()
{
    define("APPKEY", '3argexb63fdie');
    define('APPSECRET','FwWhDzljPU');
    require_once Env::get('vendor_path').'RongCloud/RongCloud.php';
    $rong = new \RongCloud\RongCloud(APPKEY,APPSECRET);
    return $rong;
}
//获取当前请求者的ip
function Getip()
{
    if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
        $cip = $_SERVER["HTTP_CLIENT_IP"];
    } elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
        $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    } elseif (!empty($_SERVER["REMOTE_ADDR"])) {
        $cip = $_SERVER["REMOTE_ADDR"];} else {
        $cip = 0;
    }
    return $cip;
}
//获取用户信息
function getuserinfo($uid){
    $info = db::name('user')->where('id',$uid)->field('id,username,avatar,mobile,mobiles,num,role,hid')->find();
    if(!$info){
        return false;
    }
    $info['avatar'] = get_file_path($info['avatar']);
    $info['username'] = urldecode($info['username']);
    return $info;
}
//将图片存到图片表
function pics($wxicon)
{
    //$wxicon = 'http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKWkiaUyh1p83Ufz67eWibdFyhmkSzibOLff4mpRMnJWNsiaiaUkHzE7OKkOqE9qTFUbOCbG1EqeR9vxog/132';
    //将网络图片 存到本地
    $img = GrabImage($wxicon);
    $info['path'] = $img;
    $info['url'] = $wxicon;
    $pics = db('admin_attachment')->where(['url'=>$wxicon])->find();
    if(!empty($pics)){
        $mtass = $pics['id'];
    }else{
        $mtass = db('admin_attachment')->insertGetId($info);
    }
    return $mtass;
}
/*
 * 获取网络图片
 * @param string $file 图片连接
 * @param string $filename 新图片名称
 * @return string  msg 路径或失败信息
 */
function GrabImage($url, $filename = "")
{
    $header = array(
        'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
        'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
        'Accept-Encoding: gzip, deflate',);
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);// 设置是否检查服务器端的证书
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    $data = curl_exec($curl);
    $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    if ($code == 200) {//把URL格式的图片转成base64_encode格式的！
        $imgBase64Code = "data:image/jpeg;base64," . base64_encode($data);
        $img_content = $imgBase64Code;//图片内容
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result))
        {
            $new_file = 'uploads/images/icon/'.time().rand(111111111,999999999) . '.png';
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img_content))))
            {
                return $new_file;
            }
        }
        return $filename;//返回新的文件名
    }else{
        return '1529665150703965928.png';//返回新的文件名
    }
}

    //极光推送-------用户端
function pushJ($uid = [], $content = '', $array = [],$type = 2,$title = '赚点呗')
{
    $tags = [];
    if($uid){
        // $tags = db::name('user')->where('id', 'in', $uid)->column('id');
        $tags = $uid;
    }
    $key = '6281ee8b307727de2f4c24db';
    $secret = '61752357ed03ba0146a82e6e';
    // $tags = array_unique($tags);
    $time = time();
    if ($tags) {
        foreach($tags as $k=>$v){
            $tags[$k] = (string)$v;
            $info = [];
            $info = db::name('msg_log')->where('uid',$v)->where('type',$array['type'])->find();
            $log = [];
            $log['uid'] = $v;
            if($array['type'] == 4){
                $log['type'] = 3;
            }else{
                $log['type'] = $array['type'];
            }
            $log['content'] = $content;
            $log['addtime'] = $time;
            if($info){
                $log['num'] = $info['num'] + 1;
                db::name('msg_log')->where('id',$info['id'])->update($log);
            }else{
                $log['num'] = 1;
                db::name('msg_log')->insert($log);
            }
        }
    }else{
        if($array['type'] == 1){
            $uu = db::name('user')->column('id');
            if($uu){
                foreach($uu as $k=>$v){
                    $info = [];
                    $info = db::name('msg_log')->where('type',1)->where('uid',$v)->find();
                    $log = [];
                    $log['uid'] = $v;
                    $log['type'] = 1;
                    $log['content'] = $content;
                    $log['addtime'] = $time;
                    if($info){
                        $log['num'] = $info['num'] + 1;
                        db::name('msg_log')->where('id',$info['id'])->update($log);
                    }else{
                        $log['num'] = 1;
                        db::name('msg_log')->insert($log);
                    }
                }
            }
        }
    }
    if($type != 3){
        if(!$tags){
            return false;
        }
    }

    require_once Env::get('root_path') . 'vendor/push/autoload.php';
    $client = new \JPush\Client($key, $secret);
    if ($array) {
        $android_notification = array(
            'title' => $title,
            'extras' => $array,
        );
        $ios_notification = array(
            'sound' => 'sound',
            "badge" => '+1',
            'extras' => $array,//type = 0提现审核（不用跳转），1官方公告，2福利圈红包消息，3评论消息，4打卡地评论，5审核消息
        );
    } else {
        $android_notification = array(
            'title' => $title,
        );
        $ios_notification = array(
            'sound' => 'sound',
        );
    }
    $contents['body'] = $content;
    $contents['title'] = $title;
    // True 表示推送生产环境，False 表示要推送开发环境；如果不指定则默认为推送开发环境
    $options = array('time_to_live' => 1, 'apns_production' => False);

    $pusher = $client->push();
    $pusher->setPlatform(['ios', 'android']);
    if($type == 1){
        $pusher->addRegistrationId($tags);
    }elseif($type == 2){
        $pusher->addAlias($tags);
    }else{
        $pusher->addAllAudience();//广播
    }
    $pusher->setNotificationAlert($content);
    $pusher->androidNotification($content, $android_notification);
    $pusher->iosNotification($contents, $ios_notification);
    $pusher->options($options);
    try {
        $a = $pusher->send();
        // dump($a);die;
    } catch (\JPush\Exceptions\JPushException $e) {
        // try something else here
        // print $e;
    }
}

/*
 * 单文件
 * @param string $file 文件名称
 * @param string $size 可上传文件的大小
 * @param string $path 文件路径
 * @return Array  data 数组
 * @retval string  code 0成功 1失败
 * @return string  msg 路径或失败信息
 */
function post_upload_one($uid, $file, $size = 11548484, $path = '/uploads/apifile')
{

    $file = request()->file($file);
    if (empty($file)) {
        $data['code'] = '2';
        $data['msg'] = '未选择图片';
        return $data;
    }
    // echo 11;die;
    // print_r($file);die;

    $size = 11548484;
    $path = '/uploads/apifile';
      if (config('upload_driver') != 'local') {
        $hook_result = Hook::listen('upload_attachment', ['file' => $file, 'from' => '', 'module' => 'api'], true);
        if (false !== $hook_result) {
            $res = $hook_result->getData();
            $data['code'] = '0';
            $data['msg'] = $res['id'];
            return $data;
            return $hook_result;
        }
    }

    $info = $file->move(config('upload_path') . DIRECTORY_SEPARATOR . $path);/*Env::get('ROOT_PATH') . '/public' . $path . '/'*/
    if ($info) {
        // 缩略图路径
        $thumb_path_name = '';
        // 图片宽度
        $img_width = '';
        // 图片高度
        $img_height = '';
        // $img = Image::open($info);
        $img_width = '';
        $img_height = '';
        // 水印功能
        // 获取附件信息
        $file_info = [
            'uid' => $uid,
            'name' => $file->getInfo('name'),
            'mime' => $file->getInfo('type'),
            'path' => str_replace('\\', '/', 'uploads/uploads/apifile/' . str_replace('\\', '/', $info->getSaveName())),
            'ext' => $info->getExtension(),
            'size' => $info->getSize(),
            'md5' => $info->hash('md5'),
            'sha1' => $info->hash('sha1'),
            'thumb' => $thumb_path_name,
            'module' => 'user',
            'width' => $img_width,
            'height' => $img_height,
        ];
        if ($id = db::name('admin_attachment')->insertGetId($file_info)) {
            $data['code'] = '0';
            $data['msg'] = $id;
            return $data;
        }
    }
    $data['code'] = '1';
    $data['msg'] = $file->getError();
    return $data;
}
/*
 * 多文件上传
 * @param int $uid 上传文件的用户id
 * @param date $file 上传文件的参数名
 * @return date数组 code==0 上传成功 msg 返回文件id多个逗号隔开
 */
function post_uploads($uid, $filename)
{
    $file = request()->file();
    if (empty($file)) {
        $data['code'] = '1';
        $data['msg'] = '图片为空';
        return $data;
    }
    $size = 11548484;
    $path = '/uploads/apifile';
    // dump($file);die;
    foreach ($file[$filename] as $k => $v) {
        if (config('upload_driver') != 'local') {
            $hook_result = Hook::listen('upload_attachment', ['file' => $v, 'from' => '', 'module' => 'api'], true);
            if (false !== $hook_result) {
                $res = $hook_result->getData();
              
                $arr[] = $res['id'];
            }
            continue;
        }
        $aa = config('upload_path');
        // print_r($path);die;
         $info = $v->move(config('upload_path') . DIRECTORY_SEPARATOR . $path);/*Env::get('ROOT_PATH') . '/public' . $path . '/'*/
        if ($info) {
            // 缩略图路径
            $thumb_path_name = '';
            // 图片宽度
            $img_width = '';
            // 图片高度
            $img_height = '';
            // $img = Image::open($info);
            $img_width = '';
            $img_height = '';
            // 水印功能
            // 获取附件信息
            $file_info = [
                'uid' => $uid,
                'name' => $v->getInfo('name'),
                'mime' => $v->getInfo('type'),
                'path' => str_replace('\\', '/', 'uploads/uploads/apifile/' . str_replace('\\', '/', $info->getSaveName())),
                'ext' => $info->getExtension(),
                'size' => $info->getSize(),
                'md5' => $info->hash('md5'),
                'sha1' => $info->hash('sha1'),
                'thumb' => $thumb_path_name,
                'module' => 'user',
                'width' => $img_width,
                'height' => $img_height,
            ];
            if ($id = db::name('admin_attachment')->insertGetId($file_info)) {
                $rr['id'] = $id;
                $rr['url'] = 'http://' . $_SERVER['HTTP_HOST'].'/'.$file_info['path'];
                $arr[] = $rr;
            }
        }
    }
    $data['code'] = '200';
    // $data['msg'] = implode(",", $arr);
    $data['msg'] = $arr;
    return $data;
}
//两个日期的天数
function diffBetweenTwoDays ($day1, $day2)
{
    $second1 = strtotime($day1);
    $second2 = strtotime($day2);
    if ($second1 < $second2) {
        $tmp = $second2;
        $second2 = $second1;
        $second1 = $tmp;
    }
    return ($second1 - $second2) / 86400;
}
/**
 * @Description: 将时间转换为几秒前、几分钟前、几小时前、几天前
 * @Author: Yang
 * @param $the_time 需要转换的时间
 * @return string
 */
function time_tran($the_time)
{
    $now_time = date("Y-m-d H:i:s", time());
    $now_time = strtotime($now_time);
    $show_time = strtotime($the_time);
    $dur = $now_time - $show_time;
    if ($dur < 0) {
        return $the_time;
    } else {
        if ($dur < 60) {
            return $dur . '秒前';
        } else {
            if ($dur < 3600) {
                return floor($dur / 60) . '分钟前';
            } else {
                if ($dur < 86400) {
                    return floor($dur / 3600) . '小时前';
                } else {
                    if ($dur < 259200) { // 3天内
                        return floor($dur / 86400) . '天前';
                    } else {
                        return $the_time;
                    }
                }
            }
        }
    }
}


//任务置顶
function tasktop($taskid,$money,$type,$dsn,$time){
    $log = [];
    $log['taskid'] = $taskid;
    $log['money'] = $money;
    $log['addtime'] = time();
    $log['type'] = $type;
    $log['dsn'] = $dsn;
    $log['time'] = $time;
    db::name('task_toporder')->insert($log);
    return true;
}
//可用加价券
function plus_coupon($uid){
    $coupon = db::name('user_coupon')->where('uid',$uid)->where('end_time > '.time())->where('status = 0')->field('id as coupon_id,money,end_time')->select();
    if($coupon){
        foreach($coupon as $k=>$v){
            $coupon[$k]['end_time'] = time('Y-m-d H:i',$v['end_time']);
        }
    }
    return $coupon;
}
